import json
import uuid

from django.contrib.auth import authenticate
from django.core.cache import cache
from django.http import HttpResponse, JsonResponse

# Create your views here.
def hello(request):
    return HttpResponse("hello")


# 登录
def login(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        print(data)
        # data = request.POST
        username = data.get('username').strip()
        password = data.get('password')
        user = authenticate(username=username, password=password)
        if user:
            token = uuid.uuid4().hex
            cache.set(token, user.id)
            res = {
                'data': {'username': username, 'password': password, 'token': token},
                'meta': {'status': 200, 'message': '用户登录成功'}
            }
        else:
            res = {
                'data': None,
                'meta': {'status': 801, 'message': '用户名或者密码错误'}
            }
    else:
        res = {
            'data': None,
            'meta': {'status': 802, 'message': '请发起POST请求'}
        }
    return JsonResponse(res)


# 登出
def logout(request):
    token = request.META.get('HTTP_AUTHORIZATION')
    cache.delete(token)
    res = {
        'data': None,
        'meta': {'status': 200, 'message': '用户退出成功！'}
    }
    return JsonResponse(res)

# 修改密码
def change_password(request):
    if request.method == 'PUT':
        data = json.loads(request.body)
        print(data)
        username = data.get('username')
        password = data.get('password')
        newPassword = data.get('newPassword')
        user = authenticate(username=username, password=password)
        if user:
            user.set_password(newPassword)
            user.save()
            res = {
                'data': {'username': username, 'password': newPassword},
                'meta': {'status': 200, 'message': '修改密码成功！'}
            }
        else:
            res = {
                'data': {},
                'meta': {'status': 201, 'message': '用户原密码错误'}
            }
        return JsonResponse(res)